package com.cjzuji.rental.service.impl;

import com.cjzuji.rental.mapper.CommissionMapper;
import com.cjzuji.rental.mapper.ConsumptionRecordMapper;
import com.cjzuji.rental.mapper.PurchaseBillMapper;
import com.cjzuji.rental.pojo.Commission;
import com.cjzuji.rental.pojo.ConsumptionRecord;
import com.cjzuji.rental.pojo.PurchaseBill;
import com.cjzuji.rental.service.ExcelImportService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExcelImportServiceImpl implements ExcelImportService {
    @Autowired
    CommissionMapper commissionMapper;
    @Autowired
    ConsumptionRecordMapper consumptionRecordMapper;
    @Autowired
    PurchaseBillMapper purchaseBillMapper;
    //佣金导入
    @Override
    //@Transactional
    public String CommissionExcel(File file){
        if (!file.exists()){return "文件不存在！";}
        //检查文件类型
        String fileName = file.getName();
        System.out.println("fileName: " +fileName);
        if (fileName == null || !fileName.toLowerCase().endsWith(".xlsx")){
            return "请选择正确的Excel文件！(.xlsx格式)";
        }
        List<Commission> commissions = new ArrayList<>();
        int successCount = 0;
        int errorCount = 0;
        try (InputStream inputStream = new FileInputStream(file)){
            //System.out.println("创建XSSFWorkbook~~: " );
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            System.out.println("获取工作表名称: " +sheet.getSheetName());
            // 跳过标题行，从第二行开始读取数据
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                try {
                    Commission commission = Commission.builder()
                            .shopId(getShopName(row.getCell(0).getStringCellValue().trim()))
                            .platformId(getPlatformName(row.getCell(1).getStringCellValue().trim()))
                            .orderId(row.getCell(2).getStringCellValue().trim())
                            .serviceAmount(row.getCell(3).getNumericCellValue())
                            .category(row.getCell(4).getStringCellValue().trim())
                            .time(getSafeDateTimeValue(row.getCell(5)))
                            .remark(row.getCell(6).getStringCellValue().trim())
                            .build();
                    //System.out.println("commission: " +commission);
                    commissionMapper.insert(commission);
                    successCount++;
                }catch (Exception e){
                    errorCount++;
                    throw new RuntimeException("第"+(i+1)+"文件解析错误");
                }
            }

            return "导入成功！";
        }catch (IOException e){
            throw new RuntimeException("文件读取失败: "+e.getMessage());
        }
    }

    //消费记录导入
    @Override
    //@Transactional
    public String ConsumptionRecordExcel(File file) {
        if (!file.exists()){return "文件不存在！";}
        //检查文件类型
        String fileName = file.getName();
        System.out.println("fileName: " +fileName);
        if (fileName == null || !fileName.toLowerCase().endsWith(".xlsx")){
            return "请选择正确的Excel文件！(.xlsx格式)";
        }
        List<ConsumptionRecord> consumptionRecords = new ArrayList<>();
        try (InputStream inputStream = new FileInputStream(file)){
            //System.out.println("创建XSSFWorkbook~~: " );
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            // 跳过标题行，从第二行开始读取数据
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                try {
                    ConsumptionRecord consumptionRecord = ConsumptionRecord.builder()
                            .shopId(getShopName(row.getCell(0).getStringCellValue().trim()))
                            .platformId(getPlatformName(row.getCell(1).getStringCellValue().trim()))
                            .orderId(row.getCell(2).getStringCellValue().trim())
                            .amount(row.getCell(3).getNumericCellValue())
                            .category(row.getCell(4).getStringCellValue().trim())
                            .consumeTime(getSafeDateTimeValue(row.getCell(5)))
                            .remark(row.getCell(6).getStringCellValue().trim())
                            .build();
                    consumptionRecordMapper.insert(consumptionRecord);
                }catch (Exception e){
                    throw new RuntimeException("文件解析错误");
                }
            }
            return "导入成功！";
        }catch (IOException e){
            throw new RuntimeException("文件读取失败: "+e.getMessage());
        }
    }

    //采购订单导入
    @Override
    @Transactional
    public String PurchaseBillExcel(File file) {
        if (!file.exists()){return "文件不存在！";}
        //检查文件类型
        String fileName = file.getName();
        System.out.println("fileName: " +fileName);
        if (fileName == null || !fileName.toLowerCase().endsWith(".xlsx")){
            return "请选择正确的Excel文件！(.xlsx格式)";
        }
        List<PurchaseBill> purchaseBills = new ArrayList<>();
        try (InputStream inputStream = new FileInputStream(file)){
            //System.out.println("创建XSSFWorkbook~~: " );
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            // 跳过标题行，从第二行开始读取数据
            for (int i = 1; i <= 92; i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                try {
                    System.out.println("开始导入: " +(i+1) + "行数据");
                    PurchaseBill purchaseBill = PurchaseBill.builder()
                            .commpany(row.getCell(0).getStringCellValue())
                            .platform(row.getCell(1).getStringCellValue())
                            .orderId(row.getCell(2).getStringCellValue())
                            .purchaseAmount(getSafeNegativeNumber(row.getCell(3)))
                            .categrory(row.getCell(4).getStringCellValue())
                            .purchaseName(row.getCell(5).getStringCellValue())
                            .time(getSafeDateTimeValue(row.getCell(6)))
                            .remark(row.getCell(7).getStringCellValue())
                            .build();
                    purchaseBillMapper.insert(purchaseBill);
                }catch (Exception e){
                    throw new RuntimeException("文件解析错误");
                }
            }
            return "导入成功！";
        }catch (IOException e){
            throw new RuntimeException("文件读取失败: "+e.getMessage());
        }
    }

    //处理负数
    private Double getSafeNegativeNumber(Cell cell) {
        if (cell == null) {
            return 0.0 ;
        }
        try {
            switch (cell.getCellType()){
                case NUMERIC:
                    return cell.getNumericCellValue();
                case STRING:
                    String str = cell.getStringCellValue().trim();
                    if (str.isEmpty()){
                        return 0.0;
                    }
                    //提取负数
                    return Double.parseDouble(str);
                case FORMULA:
                    try {
                        return cell.getNumericCellValue();
                    }catch (Exception e){
                        return 0.0;
                    }
                case BLANK:
                    return 0.0;
                default:
                    return 0.0;
            }
        }catch (Exception e){
            return 0.0;
        }
    }
    // 安全的日期时间获取方法
    private String getSafeDateTimeValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        try {
            switch (cell.getCellType()) {
                case NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // Excel日期时间格式
                        return new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
                    } else {
                        // 如果是数字但不是日期格式，按数字处理
                        double num = cell.getNumericCellValue();
                        if (num == Math.floor(num)) {
                            return String.valueOf((long) num);
                        } else {
                            return String.valueOf(num);
                        }
                    }
                default:
                    return "";
            }
        } catch (Exception e) {
            System.err.println("日期时间解析异常: " + e.getMessage());
            return "";
        }
    }
    //店铺ID
    public static int getShopName(String shopId) {
        switch (shopId) {
            case "广创":
                return 1;
            case "长九":
                return 2;
            case "稳实":
                return 3;
            case "谦莲":
                return 4;
            default:
                return 0;
        }
    }
    //平台ID
    public static int getPlatformName(String platformId) {
        switch (platformId) {
            case "优品租":
                return 1;
            case "爱租机":
                return 2;
            case "人人":
                return 3;
            case "零零":
                return 4;
            case "俏租机":
                return 5;
            case "爱豆":
                return 6;
            case "二手优品租":
                return 7;
            case "二手人人租":
                return 8;
            default:
                return 0;
        }
    }
}
